<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

require_once(APPPATH . '/controllers/super_admin' . EXT);
class Exam extends Super_admin {

    function __construct() {
        parent::__construct();

        $this->load->model(array(
            'Group_model',
            'User_model',
            'Exam_group_model',
            'Exam_model',
            'Exam_detail_model',
            'Score_model',
            'Score_detail_model',
        ));

        $this->load->helper(array(
            'security',
            'string',
        ));
    }
    /**
     * list_records
     *
     * Load information list
     *
     * @access public
     * @param int
     * @return void
     */
    function list_records($group_id) {
        $access = array('student', 'instructor');
        $this->_is_authorize($access); //check super_admin controller

        $data['group'] =  $this->Group_model->get_record(array('where' => 'group_id = "'.$group_id.'"'));

        $this->load->view('exam/list',$data);
    }
    /**
     * take_exam
     *
     * Load examination page
     *
     * @access public
     * @param int
     * @param int
     * @return void
     */
    function take_exam($group_id, $exam_id) {
        $access = array('student');
        $this->_is_authorize($access); //check super_admin controller

        //if exam already been taken redirect
        if ( $this->Score_model->exists( array('exam_id' => $exam_id, 'user_id' => _session('user_id') ) ) ) {
            _message("Exam already been taken.", 'error', FALSE);
            return redirect('exam/list_records/'.$group_id);
        }

        $data['group'] =  $this->Group_model->get_record(array('where' => 'group_id = "'.$group_id.'"'));
        $data['exam'] = $this->Exam_model->get_record(array('where' => 'exam_id = "'.$exam_id.'"'));

        $exam_detail = $this->Exam_detail_model->get_list(array(
            'where' => 'exam_id = "'.$exam_id.'"'
            ,'order_by' => 'RAND()'
        ));

        $data['generated_exam'] = $this->_generate_exam($exam_detail, $exam_id);

        $this->load->view('exam/take_exam',$data);
    }

    function print_take_exam () {
        $exam_id = $this->input->post('exam_id', TRUE);

        $data['exam'] = $this->Exam_model->get_record(array('where' => 'exam_id = "'.$exam_id.'"'));
        $data['user'] = $this->User_model->get_record(array('where' => 'user_id = "'.  _session('user_id').'"'));

        $this->load->view('print/take_exam',$data);

    }
    /**
     * _generate_exam
     *
     * Generation of exam form
     *
     * @access private
     * @param int
     * @param int
     * @return array
     */
    function _generate_exam($exam_detail, $exam_id) {
        $data = array();
        $match_answer_arr= array();
        $match_question_arr= array();

        $exam = $this->Exam_model->get_record(array(
            'where' => 'e.exam_id ="'.$exam_id.'"'
        ));

        $i_nt = $exam['identification_no_terms'];
        $m_nt = $exam['multiple_no_terms'];
        $ma_nt = $exam['match_no_terms'];
        $t_nt = $exam['true_false_no_terms'];
        
        $identification = 1;
        $multiple = 1;
        $matching = 1;
        $true_or_false = 1;

        foreach ($exam_detail as $ed) {
            if ($identification <= $i_nt) {
                array_push($data, $this->_generate_identification($ed, $identification, $i_nt) );
                $identification++;
                continue;
            }
            
            if ($multiple <= $m_nt) {
                $multiple_exam_detail = $this->Exam_detail_model->get_list(array(
                    'select' => 'definition',
                    'where' => 'exam_id = "'.$exam_id.'" AND term != "'.$ed['term'].'"'
                    ,'order_by' => 'RAND()'
                    ,'limit' => '4'
                ));

                $multiple_exam_detail[4]['definition'] = $ed['definition'];
                shuffle($multiple_exam_detail); //shuffle

                array_push($data, $this->_generate_multiple($ed, $multiple, $exam['multiple_no_terms'], $multiple_exam_detail));
                $multiple++;
                continue;
            }
            if ($matching <= $ma_nt) {
                $match_answer_arr[] = $ed['definition'];
                $match_question_arr[] = array('term' => $ed['term'],'definition' => $ed['definition'], 'match_key' => '', 'right_q' => '', 'right_key' => '');

                if ($matching == $ma_nt) {
                    $match_counter = 1;
                    shuffle($match_answer_arr); //shuffle
                    
                    $match_answer_arr = $this->_assign_key($match_answer_arr); // add letters to answer
                    $match_question_arr = $this->_map_question($match_answer_arr, $match_question_arr); //returns match question with anwser
                    
                    ksort($match_question_arr); //sort key to a, b c, ... and so fort.
                    //match question with match answer
                    foreach ($match_question_arr as $ed) {
                        array_push($data, $this->_generate_match_left($ed, $exam['match_no_terms'], $match_counter));
                        $match_counter++;
                    }
                    $match_counter = 1;
                    foreach ($match_question_arr as $ed) {
                        array_push($data, $this->_generate_match_right($ed, $exam['match_no_terms'], $match_counter));
                        $match_counter++;
                    }
                }
                $matching++;
                continue;
            }

            if ($true_or_false <= $t_nt) {
                $true_false_exam_detail = $this->Exam_detail_model->get_list(array(
                    'select' => 'definition',
                    'where' => 'exam_id = "'.$exam_id.'"'
                    ,'order_by' => 'RAND()'
                    ,'limit' => '1'
                ));

                $true_false_exam_detail[1]['definition'] = $ed['definition'];
                shuffle($true_false_exam_detail); //shuffle

                array_push($data, $this->_generate_true_false($ed, $true_or_false, $t_nt, $true_false_exam_detail));
                $true_or_false++;
                continue;
            }
        }

        return $data;
    }
    /**
     * _generate_identification
     *
     * Generation of exam form (identification)
     *
     * @access private
     * @param array
     * @param int
     * @param int
     * @return string
     */
    function _generate_identification($ed, $identification, $no_terms) {
        $code = '';
        if ($identification == 1) {
            $code = '<h3 class="title">'.$no_terms.' - Written Questions</h2>';
            $code .= '<div id = "written1" class="unit">';
        }
                $code .= '<div class="line">';
                    $code .= '<label for="" class="bold">'.$identification.'. <span>'.$ed['term'].'</span>:</label>';
                    $code .= '<div class="field clear" style="height:auto">';
                    $code .= '<input type="text" name="written_'.$identification.'" id="written_'.$identification.'" ans = "'.$ed['definition'].'" />';
                    $code .= '</div>';
                $code .= '</div>';
        if ($identification == $no_terms) {
            $code .= '</div>';
            $code .= '<div class = "clear"></div>';
        }
        
        return $code;
    }
    /**
     * _generate_multiple
     *
     * Generation of exam form (mutiple choice)
     *
     * @access private
     * @param array
     * @param int
     * @param int
     * @param array
     * @return string
     */
    function _generate_multiple($ed, $multiple, $no_terms, $multiple_exam_detail) {
        
        $code = '';
        if ($multiple == 1) {
            $code = '<h3 class="title">'.$no_terms.' Multiple Choice Questions</h2>';
            $code .= '<div id = "multiple1" class="unit">';
        }
                $code .= '<div class="line">';
                    $code .= '<label style ="" for="" class="bold">'.$multiple.'. <span>'.$ed['term'].'</span>:</label>';
                    $code .= '<div class="field clear" style="height:auto">';
                    $code .= '<ul>';
                        $a_is_correct = ($multiple_exam_detail[0]['definition'] == $ed['definition']) ? '1' : '0';
                        $b_is_correct = ($multiple_exam_detail[1]['definition'] == $ed['definition']) ? '1' : '0';
                        $c_is_correct = ($multiple_exam_detail[2]['definition'] == $ed['definition']) ? '1' : '0';
                        $d_is_correct = ($multiple_exam_detail[3]['definition'] == $ed['definition']) ? '1' : '0';
                        $e_is_correct = ($multiple_exam_detail[4]['definition'] == $ed['definition']) ? '1' : '0';

                        $code .= '<li>a. <input value = "'.$a_is_correct.'" type="radio" name="multiple_'.$multiple.'" id="multiple_a_'.$multiple.'" /><span>'.$multiple_exam_detail[0]['definition'].'</span></li>';
                        $code .= '<li>b. <input value = "'.$b_is_correct.'" type="radio" name="multiple_'.$multiple.'" id="multiple_b_'.$multiple.'" /><span>'.$multiple_exam_detail[1]['definition'].'</span></li>';
                        $code .= '<li>c. <input value = "'.$c_is_correct.'" type="radio" name="multiple_'.$multiple.'" id="multiple_c_'.$multiple.'" /><span>'.$multiple_exam_detail[2]['definition'].'</span></li>';
                        $code .= '<li>d. <input value = "'.$d_is_correct.'" type="radio" name="multiple_'.$multiple.'" id="multiple_d_'.$multiple.'" /><span>'.$multiple_exam_detail[3]['definition'].'</span></li>';
                        $code .= '<li>e. <input value = "'.$e_is_correct.'" type="radio" name="multiple_'.$multiple.'" id="multiple_e_'.$multiple.'" /><span>'.$multiple_exam_detail[4]['definition'].'</span></li>';
                    $code .= '</ul>';
                    $code .= '</div>';
                $code .= '</div>';
        if ($multiple == $no_terms) {
            $code .= '</div>';
            $code .= '<div class = "clear"></div>';
        }

        return $code;
    }
    /**
     * _generate_match_left
     *
     * Generation of exam form (matching type - left side)
     *
     * @access private
     * @param array
     * @param int
     * @param int
     * @return string
     */
    function _generate_match_left($ed, $no_terms, $match) {
        $code = '';
        if ($match == 1) {
            $code = '<h3 class="title">'.$no_terms.' Matching Type Questions</h2>';
            $code .= '<div id = "match1" class="unit">';
                $code .= '<span>Type the letters only.</span>';
        }
                $code .= '<div class="line">';
                    $code .= '<label style ="" for="" class="bold">'.$match.'. <span>'.$ed['term'].'</span>:</label>';
                    $code .= '<div class="field clear" style="height:auto">';
                        $code .= '<input style = "width:100px" maxlength="1" match = "'.$ed['match_key'].'" type="text" name="match_'.$match.'" id="match_'.$match.'" />';
                    $code .= '</div>';
                $code .= '</div>';
        if ($match == $no_terms) {
            $code .= '</div>';
        }

        return $code;
    }
    /**
     * _generate_match_right
     *
     * Generation of exam form (matching type - right side)
     *
     * @access private
     * @param array
     * @param int
     * @param int
     * @return string
     */
    function _generate_match_right($ed, $no_terms, $match) {
        $code = '';
        if ($match == 1) {
            $code .= '<div id ="match-right1" class="unitExt">';
        }
                $code .= '<div class="line">';
                    $code .= '<label style ="" for="" class="bold">'.$ed['right_key'].':</label>';
                    $code .= '<div class="field" style="height:auto">';
                        $code .= $ed['right_q'];
                    $code .= '</div>';
                $code .= '</div>';
        if ($match == $no_terms) {
            $code .= '</div>';
            $code .= '<div class = "clear"></div>';
        }

        return $code;
    }
    /**
     * _generate_true_false
     *
     * Generation of exam form (true or false)
     *
     * @access private
     * @param array
     * @param int
     * @param int
     * @param array
     * @return string
     */
    function _generate_true_false($ed, $true_or_false, $no_terms, $true_false_exam_detail) {
        $code = '';
        if ($true_or_false == 1) {
            $code = '<h3 class="title">'.$no_terms.' True or False Questions</h2>';
            $code .= '<div id = "truefalse1" class="unit">';
        }
                $code .= '<div class="line">';
                    $code .= '<label for="" class="bold">'.$true_or_false.'. <span>'.$ed['term'].' -> '.$true_false_exam_detail[0]['definition'].'</span></label>';
                    $code .= '<div class="field clear" style="height:auto">';
                        $is_true = ($true_false_exam_detail[0]['definition'] == $ed['definition']) ? '1' : '0';
                        $is_false = ($true_false_exam_detail[0]['definition'] != $ed['definition']) ? '1' : '0';
                        $code .= '<div>';
                            $code .= '<input type="radio" name="tf_'.$true_or_false.'" id="tf_'.$true_or_false.'_t" value = "'.$is_true.'" /><span>True</span>';
                            $code .= '<input type="radio" name="tf_'.$true_or_false.'" id="tf_'.$true_or_false.'_f" value = "'.$is_false.'" /><span>False</span>';
                        $code .= '</div>';
                    $code .= '</div>';
                $code .= '</div>';
        if ($true_or_false == $no_terms) {
            $code .= '</div>';
            $code .= '<div class = "clear"></div>';
        }

        return $code;
    }
    /**
     * _assign_key
     *
     * Assign letters for matching type
     *
     * @access private
     * @param array
     * @return array
     */
    function _assign_key($match_answer_arr) {
        $i = -1;
        $data = array();
        $keys = array('a', 'b', 'c', 'd' ,'e'); //up to e only

        foreach($match_answer_arr as $maa) {
            $data[$keys[$i+1]] = $maa;
            $i++;
        }
        
        return $data;
    }
    /**
     * _map_question
     *
     * Map question to correct answer for matching type
     *
     * @access private
     * @param array
     * @param array
     * @return array
     */
    function _map_question($match_answer_arr, $match_question_arr) {
        $b = -1;

        foreach($match_question_arr as $i => $mqa) {
            foreach($match_answer_arr as $key => $maa) {
                if ($mqa['definition'] == $maa) {
                    $match_question_arr[$i]['match_key'] = $key;
                    continue;
                }
            }
        }

        foreach($match_answer_arr as $key => $maa) {
            
            $match_question_arr[$b+1]['right_q'] = $maa;
            $match_question_arr[$b+1]['right_key'] = $key;
            $b++;
        }
        
        return $match_question_arr;
    }
    /**
     * get_exams
     *
     * get exam list
     *
     * @access public
     * @return string
     */
    function get_exams() {

        $search = $this->input->post('search', TRUE);
        $date_posted = $this->input->post('date_posted', TRUE);
        $date_posted = ita_to_mysql($date_posted);
        
        $group_id = $this->input->post('group_id', TRUE);

        $where = 'e.exam_id != "!@#"';

        $join_exam_group = array(
            'table' => EXAMS_GROUPS . ' eg',
            'condition' => 'eg.exams_exam_id = e.exam_id AND eg.groups_group_id = "'.$group_id.'"',
        );

        $join_exam_details = array(
            'table' => EXAM_DETAILS . ' ed',
            'condition' => 'ed.exam_id = e.exam_id',
            'join' => 'LEFT',
        );

        //Filter by
        $filter = ( ! empty($search) )  ? 'e.exam_name LIKE "%' .$search.'%" ' : NULL;  //lesson name
        $filter .= ( $date_posted != '0000-00-00' && ! empty($search) ) ? ' AND e.date_posted = "' .$date_posted.'" ' : NULL;  //with exam name
        $filter .= ( $date_posted != '0000-00-00' &&  empty($search) ) ? ' e.date_posted = "' .$date_posted.'" ' : NULL;  //without exam name
    
        $where .= ( ! empty($filter) ) ? ' AND  '.$filter : NULL;

        $select = 'e.exam_id, e.exam_name, eg.groups_group_id, e.exam_kind, e.date_posted, e.status, ed.term';

        $order_by = $this->input->post('sidx') . ' ' . $this->input->post('sord');

        $args = array(
                    'select' => $select,
                    'where' =>  $where,
                    'join' => array($join_exam_group, $join_exam_details),
                    'order_by' => $order_by,
                    'group_by' => 'e.exam_id'
        );

        //For pagination
        $page = $this->input->post('page');
        $total = count($this->Exam_model->get_list($args));

        $num_pages = ceil($total / LIMIT);

        if ($page > $num_pages && $total <> 0) {
            $page = $num_pages;
        }

        $offset = (LIMIT * $page) - LIMIT;

        //PUSH THIS VALUE INTO ARGS
        $args['limit'] = LIMIT;
        $args['offset'] = $offset;
        $args['resource_id'] = TRUE;
        //end Pagination

        $records = $this->Exam_model->get_list($args);

        $jsn_records = '[]';
        if ($total > 0) {
            $jsn_records = $this->json_formatter->_run($records, 'exam_id');
        }

        echo '{"page": "' . $page . '", "total": "' . $num_pages . '", "records": "' . $total . '", "rows": ' . $jsn_records . '}';
    }
    /**
     * add
     *
     * Load add form
     *
     * @access public
     * @param int
     * @return void
     */
    function add($group_id = 0){
        $access = array('instructor');
        $this->_is_authorize($access); //check super_admin controller

        $data = array(
            'exam_id' => 0,
            'exam_name' => '',
            'group_id' => $group_id,
            'no_of_terms' => 0,
            'identification_no_terms' => 0,
            'multiple_no_terms' => 0,
            'match_no_terms' => 0,
            'true_false_no_terms' => 0,
            'exam_kind' => '',
        );
        
        $this->load->view('exam/form', $data);
        
    }
    function add_details($group_id = 0, $exam_id = 0){
        $access = array('instructor');
        $this->_is_authorize($access); //check super_admin controller


        $params = array(
                'select' => '*',
                'where' => array('exam_id' => $exam_id),
        );

        $e_details= $this->Exam_detail_model->get_record($params);

        if ( ! empty ($e_details) ) redirect('exam/list_records/'.$group_id); //redirect if exam details has already have data.

        $data = array(
            'exam_id' => $exam_id,
            'group_id' => $group_id,
            'exam' => $this->Exam_model->get_record($params),
        );

        $this->load->view('exam/add_details', $data);

    }
    
    function view($group_id, $id){
        $access = array('instructor');
        $this->_is_authorize($access); //check super_admin controller
        
        $params = array(
                'select' => 'e.*',
                'where' => array('e.exam_id' => $id),
                'order_by' => NULL
        );

        $data = $this->Exam_model->get_record($params);
        $data['group_id'] = $group_id;

        $params = array(
                'select' => 'ed.*',
                'where' => array('ed.exam_id' => $id),
                'order_by' => NULL
        );

        $data['exam_details'] = $this->Exam_details_model->get_list($params);

        $this->load->view('exam/display', $data);
    }
    
    function submit(){
        
        $response = FALSE;
        $exam_id = $this->input->post('exam_id', TRUE);
        $group_id = $this->input->post('group_id', TRUE);

        $data = array(
            'exam_name' => $this->input->post('exam_name',TRUE),
            'exam_kind' => $this->input->post('exam_kind',TRUE),
            'identification_no_terms' => $this->input->post('identification_no_terms',TRUE),
            'multiple_no_terms' => $this->input->post('multiple_no_terms',TRUE),
            'match_no_terms' => $this->input->post('match_no_terms',TRUE),
            'true_false_no_terms' => $this->input->post('true_false_no_terms',TRUE),
            'status' => 'Inactive',
            'date_posted' => pdate(),
        );

        //Add all no of terms
        $data['no_of_terms'] = $data['identification_no_terms'];
        $data['no_of_terms'] += $data['multiple_no_terms'];
        $data['no_of_terms'] += $data['match_no_terms'];
        $data['no_of_terms'] += $data['true_false_no_terms'];

        if (empty($exam_id)) {

            $exam_id = $this->Exam_model->_insert($data);
                    
            $data_exam_group = array(
                'exams_exam_id' => $exam_id,
                'groups_group_id' => $group_id
            );

            $this->Exam_group_model->_insert($data_exam_group);

            redirect('exam/add_details/'.$group_id.'/'.$exam_id);

        } 
    }

    function submit_details(){

        $response = FALSE;
        $exam_id = $this->input->post('exam_id', TRUE);

        $params = array(
            'select' => 'e.no_of_terms',
            'where' => array('e.exam_id' => $exam_id),
        );

        $exam = $this->Exam_model->get_record($params);

        for  ($i =  1; $i <= $exam['no_of_terms']; $i++) {
            $data = array(
                'exam_id' => $exam_id,
                'term' => $this->input->post('terms_'.$i, TRUE),
                'definition' => $this->input->post('definition_'.$i, TRUE),
            );

            $exam_detail_id = $this->Exam_detail_model->_insert($data);
        }

        $msg = sprintf(lang('cms_add_success'), "Exam");

        $response = TRUE;
        _success($msg, FALSE);
        echo json_encode($response);

    }

    function save_score(){

        $exam_id = $this->input->post('exam_id', TRUE);
        $group_id = $this->input->post('group_id', TRUE);

        $mutiples_ids = $this->input->post('mutiples_ids', TRUE);
        $identification_ids = $this->input->post('identification_ids', TRUE);
        $matching_ids = $this->input->post('matching_ids', TRUE);
        $truefalse_ids = $this->input->post('truefalse_ids', TRUE);
        $actual_score_h = $this->input->post('actual_score_h', TRUE);
        $total_score_h = $this->input->post('total_score_h', TRUE);

        $mutiples_ids = explode("|", $mutiples_ids); //convert to array
        $identification_ids = explode("|", $identification_ids); //convert to array
        $matching_ids = explode("|", $matching_ids); //convert to array
        $truefalse_ids = explode("|", $truefalse_ids); //convert to array

        $data = array(
            'user_id' => _session('user_id'),
            'exam_id' => $exam_id,
            'actual_score' => $actual_score_h,
            'over_score' => $total_score_h,
        );

        $score_id = $this->Score_model->_insert($data);
        
        foreach ($identification_ids as $idenid) {
            $answer = $this->input->post('written_'.$idenid, TRUE);
            $answer = explode("|", $answer);

            $data = array(
                'score_id' => $score_id
                ,'question' => $this->input->post('writtenq_'.$idenid, TRUE)
                ,'answer' => $answer[0]
                ,'remark' => $answer[1]
                ,'exam_type' => 'Identification'
            );

            $score_detail_id = $this->Score_detail_model->_insert($data);
        }
        foreach ($mutiples_ids as $muid) {
            $answer = $this->input->post('multiple_'.$muid, TRUE);
            $answer = explode("|", $answer);

            $data = array(
                'score_id' => $score_id
                ,'question' => $this->input->post('multipleq_'.$muid, TRUE)
                ,'answer' => $answer[0]
                ,'remark' => $answer[1]
                ,'exam_type' => 'Multiple Choice'
            );

            $score_detail_id = $this->Score_detail_model->_insert($data);

        }
        foreach ($matching_ids as $matchid) {
            $answer = $this->input->post('match_'.$matchid, TRUE);
            $answer = explode("|", $answer);

            $data = array(
                'score_id' => $score_id
                ,'question' => $this->input->post('matchq_'.$matchid, TRUE)
                ,'answer' => $answer[0]
                ,'remark' => $answer[1]
                ,'exam_type' => 'Matching Type'
            );

            $score_detail_id = $this->Score_detail_model->_insert($data);
        }
        foreach ($truefalse_ids as $tfid) {
            $answer = $this->input->post('tf_'.$tfid, TRUE);
            $answer = explode("|", $answer);

            $data = array(
                'score_id' => $score_id
                ,'question' => $this->input->post('tfq_'.$tfid, TRUE)
                ,'answer' => $answer[0]
                ,'remark' => $answer[1]
                ,'exam_type' => 'True or False'
            );

            $score_detail_id = $this->Score_detail_model->_insert($data);
        }

        echo json_encode(TRUE);
    }
    
    function open_exam() {
        $access = array('instructor');
        $this->_is_authorize($access); //check super_admin controller

        $where = array('exam_id' => $this->input->post('exam_id', TRUE));
        $data['status'] = 'Active';
        
        $this->Exam_model->_update($where, $data);

        _message("Exam successfully opened.", 'success', FALSE);

        echo json_encode(TRUE);
    }
    function close_exam() {
        $access = array('instructor');
        $this->_is_authorize($access); //check super_admin controller

        $where = array('exam_id' => $this->input->post('exam_id', TRUE));
        $data['status'] = 'Closed';

        $this->Exam_model->_update($where, $data);

        _message("Exam successfully closed.", 'success', FALSE);
        
        echo json_encode(TRUE);
    }
    function is_exam_close() {
        $access = array('instructor', 'student');
        $this->_is_authorize($access); //check super_admin controller

        $where = array(
            'exam_id' => $this->input->post('exam_id', TRUE),
            'status' => 'Closed'
        );

        echo json_encode($this->Exam_model->exists($where));
    }
}
/* End of file exam.php */
/* Location: ./application/controllers/exam.php */
